<template>
  <div class="infoAttestation front-color">
    <div class="pageTitle">
      <h1>{{$t('myAdd.infoAttestation.certificationReal')}}</h1>
      <span class="back pointer" @click="goBack">< {{$t('myAdd.infoAttestation.backPersonalInfo')}}</span>
    </div>
    <p class="titleDes">{{$t('myAdd.infoAttestation.primaryVerifyDes')}}</p>
    <div class="noC1" v-if="authNewLevel === 'C0'">
      <!-- 表单区域 -->
      <div class="fillInfo" v-if="formList.countryCode">
        <inline-input
          :property = "formList.countryCode"
          v-model="formList.countryCode.value"
          v-on:onevents="somethings" >
        </inline-input>
        <div class="name-surname clearfix">
          <div class="name-surname-left">
            <inline-input
              :property = "formList.familyName"
              v-model="formList.familyName.value"
              v-on:onevents="somethings" >
            </inline-input>
          </div>
          <div class="name-surname-right">
            <inline-input
              :property = "formList.name"
              v-model="formList.name.value"
              v-on:onevents="somethings" >
            </inline-input>
          </div>
        </div>
        <div class="certificateTypeDiv" style="height: 0; overflow: hidden;padding: 0;">
          <inline-input
            :property = "formList.certificateType"
            v-model="formList.certificateType.value"
            v-on:onevents="somethings">
          </inline-input>
          <p class="countryerrtext" v-if="countryerrtext">{{$t('personal.placeholder_19')}}</p>
        </div>
        <div class="certificateTypeDiv clearfix">
          <div class="subTitle">{{$t('myAdd.infoAttestation.documentType')}}</div>
          <div class="id_card pointer" @click="chooseCertificateType('86')"><div class="checkMark" :class="{select: certificateType === '1'}"><div class="insideCycle"></div></div>{{$t('myAdd.infoAttestation.idCard')}}</div>
          <div class="passPort pointer" @click="chooseCertificateType('000')"><div class="checkMark" :class="{select: certificateType === '2'}"><div class="insideCycle"></div></div>{{$t('myAdd.infoAttestation.passport')}}</div>
        </div>
        <p class="countryerrtext" v-if="countryerrtext">{{$t('personal.placeholder_19')}}</p>
        <inline-input
          :property = "formList.certificateNumber"
          v-model="formList.certificateNumber.value"
          v-on:onevents="somethings">
        </inline-input>
      </div>
      <!-- 提交 -->
      <div class="subDiv button-inline">
        <button class="submit" @click="submit">{{$t('myAdd.infoAttestation.submit')}}</button>
      </div>
    </div>
    <div class="hasC1" v-else>
      <div class="c1Info">
        <p class="informUser"><span><i class="icon-true_icon"></i></span><span>{{$t('myAdd.infoAttestation.identityInfo')}}</span></p>
        <div class="name_info clearfix">
          <div class="label">
            <P>{{$t('myAdd.infoAttestation.countryShip')}}</P>
            <P>{{$t('myAdd.infoAttestation.licenseNum')}}</P>
            <P>{{$t('myAdd.infoAttestation.familyName')}}</P>
          </div>
          <div class="cont">
            <P>{{countryName}}</P>
            <P>{{showCertificateNumber}}</P>
            <P>{{c1Data.familyName + c1Data.name}}</P>
          </div>
        </div>
      </div>
    </div>
    <!-- 上传身份证 -->
    <div class="content-block clearfix" v-if="authNewLevel === 'C1'">
      <template v-for="(item, key, index) in upload_form">
        <upload-file
          :title='item.title'
          :name = 'item.name'
          :remarks="item.remarks"
          :errorInfo = "item.errorInfo"
          :caseImg='item.caseImg'
          :defaultImg='item.imagesUrl'
          v-on:onevents="uploadImg" >
        </upload-file>
      </template>
      <div class="button-inline">
        <button class="submit" @click="submitUpload">{{$t('myAdd.infoAttestation.submit')}}</button>
      </div>
    </div>
    <p v-if="userinfo"></p>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import InlineInput from '@/components/common/inlineInput'
import UploadFile from '@/components/common/upload'

import caseImgPasscard1 from '../../../../assets/img/passcard1.jpg'
import caseImgPasscard2 from '../../../../assets/img/passcard2.jpg'
import caseImgPasscard3 from '../../../../assets/img/passcard3.jpg'

import caseImgIdcard1 from '../../../../assets/img/idcard1.jpg'
import caseImgIdcard2 from '../../../../assets/img/idcard2.jpg'
import caseImgIdcard3 from '../../../../assets/img/passcard3.jpg'
export default {
  name: 'infoAttestation',
  data () {
    return {
      formList: {},
      flas: true,
      countryerrtext: null,
      certificateType: '1',
      countryCode: '6',
      countryName: '',
      showCertificateNumber: '',
      authNewLevel: '',
      upload_form: {},
      c1Data: {
        countryCode: null,
        certificateNumber: null,
        certificateType: null,
        name: null,
        familyName: null
      }
    }
  },
  components: {
    InlineInput,
    UploadFile
  },
  mounted () {
    this.formList = this.formList_obj
    this.upload_form = this._upload_form
  },
  watch: {
    'formList_obj' (val) {
      this.formList = val
    },
    '_upload_form' (val) {
      this.upload_form = val
    },
    authNewLevel (newVal) {
      if (newVal === 'C1') {
        this.countryCodes()
        this.certificateType = this.userinfo.certificateType
      }
    },
    'c1Data.certificateNumber' (newVal) {
      if (newVal) {
        let certificateNumber = newVal
        certificateNumber = /^(.{4})(.*)(.{4})$/.exec(certificateNumber)
        let star = ''
        for (let i = 0; i < certificateNumber[2].length; i++) {
          star += '*'
        }
        this.showCertificateNumber = certificateNumber[1] + star + certificateNumber[3]
      }
    }
  },
  computed: {
    ...mapState({
      userinfo ({baseData: {_user}}) {
        // 如果是 已认证 或者 待审核状态 直接跳转至个人中心页面
        if (_user) {
          this.authNewLevel = _user.authNewLevel
          if (_user.authNewLevel === 'C2' || _user.authLevel === 0) { // _user.authLevel === 0 未审核
            this.$router.push({
              path: '/personal/information',
              query: {
                tab: 'information'
              }
            })
          }
          if (_user.authNewLevel === 'C1') {
            this.c1Data.certificateNumber = _user.certificateNumber
            this.c1Data.certificateType = _user.certificateType
            this.c1Data.name = _user.certificateName
            this.c1Data.familyName = _user.certificateFamilyName
            this.c1Data.countryCode = _user.countryCode
          }
        }
        return _user || false
      }
    }),
    formList_obj () {
      return {
        countryCode: { // 国籍
          title: this.$t('personal.nationality'),
          formType: 'countryCode',
          name: 'countryCode',
          placeholder: this.$t('personal.placeholder_1'),
          value: this.$store.state.baseData.default_code
        },
        certificateType: { // 证件类型
          title: this.$t('personal.certificateType'),
          formType: 'select',
          placeholder: this.$t('personal.placeholder_2'),
          name: 'certificateType',
          value: '1',
          optionList: [
            {value: this.$t('personal.China_id'), code: '1'},
            {value: this.$t('personal.passport'), code: '2'}
          ]
        },
        familyName: { // 姓氏
          title: this.$t('personal.Surname'),
          placeholder: this.$t('personal.Surname'),
          formType: 'text',
          name: 'familyName',
          value: ''
        },
        name: { // 名称
          title: this.$t('personal.name'),
          placeholder: this.$t('personal.name'),
          formType: 'text',
          name: 'name',
          value: ''
        },
        certificateNumber: { // 证件号码
          title: this.$t('personal.Certificate'),
          formType: 'text',
          placeholder: this.$t('personal.Certificate'),
          name: 'certificateNumber',
          value: ''
        }
      }
    },
    _upload_form () {
      if (this.certificateType === 1) {
        return {
          firstPhoto: {
            title: this.$t('personal.placeholder_3'),
            remarks: this.$t('personal.placeholder_4'),
            caseImg: caseImgIdcard1,
            name: 'firstPhoto',
            errorInfo: '',
            imagesUrl: null,
            value: null
          },
          secondPhoto: {
            title: this.$t('personal.placeholder_5'),
            remarks: this.$t('personal.placeholder_4'),
            caseImg: caseImgIdcard2,
            name: 'secondPhoto',
            errorInfo: '',
            imagesUrl: null,
            value: null
          },
          thirdPhoto: {
            title: this.$t('personal.placeholder_7'),
            remarks: this.$t('personal.placeholder_8') + '<br />' + this.$t('personal.placeholder_9'),
            caseImg: caseImgIdcard3,
            name: 'thirdPhoto',
            errorInfo: '',
            imagesUrl: null,
            value: null
          }
        }
      } else {
        return {
          firstPhoto: {
            title: this.$t('personal.passportCover'),
            remarks: this.$t('personal.placeholder_4'),
            caseImg: caseImgPasscard1,
            name: 'firstPhoto',
            errorInfo: '',
            imagesUrl: null,
            value: null
          },
          secondPhoto: {
            title: this.$t('personal.placeholder_6'),
            remarks: this.$t('personal.placeholder_4'),
            caseImg: caseImgPasscard2,
            name: 'secondPhoto',
            errorInfo: '',
            imagesUrl: null,
            value: null
          },
          thirdPhoto: {
            title: this.$t('personal.placeholder_7'),
            remarks: this.$t('personal.placeholder_8') + '<br />' + this.$t('personal.placeholder_9'),
            caseImg: caseImgPasscard3,
            name: 'thirdPhoto',
            errorInfo: '',
            imagesUrl: null,
            value: null
          }
        }
      }
    }
  },
  methods: {
    somethings (data) {
      if (data.handleType === 'selected' && data.name === 'certificateType') {
        this.selected(data)
      }
      if (data.handleType === 'selectedCountryCode' && data.name === 'countryCode') {
        this.countryCode = data.value.code
        this.chooseCertificateType(data.value.code)
      }
    },
    selected (data) {
      if (data.name === 'certificateType' && data.value.code !== this.certificateType) {
        this.certificateType = data.value.code
        if (data.value.code === '1') {
          if (this.countryCode !== '86' && this.countryCode !== '886') {
            this.countryerrtext = true
          } else {
            this.countryerrtext = false
          }
        } else {
          this.countryerrtext = false
        }
      }
    },
    submit () {
      let data = {}
      let fla = true
      for (let item in this.formList) {
        if (this.formList[item].value !== undefined && !this.formList[item].value) {
          this.$set(this.formList[item], 'errorInfo', this.$t('personal.text_7') + this.formList[item].title)
          // this.$store.dispatch('setTipState', {text: this.$t('personal.error_002'), type: 'error'})
          fla = false
        } else {
          data[item] = this.formList[item].value
        }
      }
      data.countryCode = data.countryCode.split('+')[1]
      if (data.certificateType === '2' && (data.countryCode === '86' || data.countryCode === '886')) {
        fla = false
        this.countryerrtext = true
      } else {
        this.countryerrtext = false
      }
      if (!fla) return false
      if (!this.flas) return false
      this.flas = false
      this.axios({
        url: this.$store.state.url.personal.primary_realname,
        headers: {},
        params: data,
        method: 'post'
      }).then(res => {
        if (res.code.toString() === '0') {
          this.$store.dispatch('getCommonUser_info')
          this.$store.dispatch('setTipState', {text: res.msg})
        } else {
          this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
        }
        this.flas = true
      }).catch(() => {
        this.flas = true
      })
    },
    // 选择证件类型
    chooseCertificateType (code) {
      if (code !== '86' && code !== '886') {
        this.$nextTick(() => {
          this.certificateType = '2'
          this.formList['certificateType'].value = '2'
          this.formList['certificateType'].optionList = [
            {value: this.$t('personal.passport'), code: '2'},
            {value: this.$t('personal.China_id'), code: '1'}
          ]
          this.countryerrtext = true
        })
      } else {
        this.certificateType = '1'
        this.$nextTick(() => {
          this.formList['certificateType'].value = '1'
          this.formList['certificateType'].optionList = [
            {value: this.$t('personal.China_id'), code: '1'},
            {value: this.$t('personal.passport'), code: '2'}
          ]
        })
        this.countryerrtext = false
      }
    },
    // 传图片
    uploadImg (data) {
      if (data.value.filenameStr) {
        this._upload_form[data.name].imagesUrl = data.value.base_image_url + data.value.filenameStr
        this._upload_form[data.name].value = data.value.filenameStr
      } else {
        this._upload_form[data.name].imagesUrl = data.value.base_image_url + data.value.filename
        this._upload_form[data.name].value = data.value.filename
      }
      this._upload_form[data.name].errorInfo = ''
    },
    // 上传图片提交
    submitUpload () {
      let data = {}
      let fla = true
      for (let item in this.c1Data) {
        if (!this.c1Data[item]) {
          this.$store.dispatch('setTipState', {text: this.$t('myAdd.personal.c1verify'), type: 'error'})
          this.$router.push('/personal/information')
          return false
        }
      }
      for (let item in this._upload_form) {
        if (this._upload_form[item].value !== undefined && !this._upload_form[item].value) {
          // this.$set(this._upload_form[item], 'errorInfo', )
          this._upload_form[item].errorInfo = this.$t('personal.q_upload') + this._upload_form[item].title
          this.upload_form = this._upload_form
          fla = false
        } else {
          data[item] = this._upload_form[item].value
        }
      }
      Object.assign(data, this.c1Data)
      if (!fla) return false
      if (!this.flas) return false
      this.flas = false
      this.axios({
        url: this.$store.state.url.personal.auth_realname,
        headers: {},
        params: data,
        method: 'post'
      }).then((data) => {
        if (data.code === '0') {
          this.$store.dispatch('getCommonUser_info')
          this.$router.push({
            path: '/personal/information',
            query: {
              tab: 'information'
            }
          })
          this.$store.dispatch('setTipState', this.$t('personal.submitCuccess'))
        } else {
          this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
        }
        this.flas = true
      }).catch(() => {
        this.flas = true
      })
    },
    // 获取国家区号
    countryCodes () {
      let Code = this.$t('public.countryCodes')
      Code.forEach(item => {
        let obj = {}
        obj.code = '+' + item.split('+')[1]
        obj.value = item.split('+')[0]
        this.userinfo.countryCode === obj.code && (this.countryName = obj.value)
      })
    },
    // 返回
    goBack () {
      this.$router.go(-1)
    }
  }
}
</script>
